package com.ruoyi.system.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.Control.CbkTelRecord;
import com.ruoyi.system.Control.ChatRecord;
import com.ruoyi.system.Control.Record;
import com.ruoyi.system.domain.QChat;
import com.ruoyi.system.domain.QService;
import com.ruoyi.system.domain.QServiceNowork;
import com.ruoyi.system.service.IQChatService;
import com.ruoyi.system.service.IQServiceNoworkService;
import com.ruoyi.system.service.IQServiceService;
import com.ruoyi.system.service.ISmsService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.util.StringUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 聊天记录Controller
 *
 * @author ruoyi
 * @date 2024-06-26
 */
@Controller
@RequestMapping("/system/chat")
public class QChatController extends BaseController {
    private String prefix = "system/chat";

    @Autowired
    private IQChatService qChatService;

    @Autowired
    private ISmsService smsService;

    @Autowired
    private IQServiceService iqServiceService;

    @Autowired
    private IQServiceNoworkService qServiceNoworkService;



    @RequiresPermissions("system:chat:view")
    @GetMapping()
    public String chat() {
        return prefix + "/chat";
    }

    /**
     * 查询聊天记录列表
     */
    @CrossOrigin
    //@RequiresPermissions("system:chat:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(QChat qChat) {
        startPage();
        List<QChat> list = qChatService.selectQChatList(qChat);
        if (list == null) return null;
        List<QChat> res = new ArrayList<QChat>();
        if (list.size() > 0) {
            QChat qChat1 = new QChat();
            qChat1 = list.get(list.size() - 1);
            res.add(qChat1);
        } else {
            res = null;
        }
        return getDataTable(res);
    }

    /**
     * 导出聊天记录列表
     */
    @CrossOrigin
    @RequiresPermissions("system:chat:export")
    @Log(title = "聊天记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(QChat qChat) {
        List<QChat> list = qChatService.selectQChatList(qChat);
        ExcelUtil<QChat> util = new ExcelUtil<QChat>(QChat.class);
        return util.exportExcel(list, "聊天记录数据");
    }

    /**
     * 新增聊天记录
     */
    @CrossOrigin
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }


    //java 比较两时间字符串大小 ,实现 时间上的迟到、早退判断

    public static boolean compTime(String s1, String s2, String gtlt) {
        if (s1.indexOf(":") < 0 || s1.indexOf(":") < 0) {
            System.out.println("格式不正确");
        } else {
            String[] array1 = s1.split(":");
            int total1 = Integer.valueOf(array1[0]) * 3600
                    + Integer.valueOf(array1[1]) * 60
                    // + Integer.valueOf(array1[2]);
                    ;
            // System.out.println(total1);
            String[] array2 = s2.split(":");
            int total2 = Integer.valueOf(array2[0]) * 3600
                    + Integer.valueOf(array2[1]) * 60;
            // + Integer.valueOf(array2[2]);
            // System.out.println(total2);
            if ("gt".equalsIgnoreCase(gtlt)) {// 大于等于
                return total1 - total2 >= 0 ? true : false;
            } else if ("lt".equalsIgnoreCase(gtlt)) {
                return total1 - total2 <= 0 ? true : false;
            }
        }
        return false;
    }


    /**
     * 新增保存聊天记录
     */
    @CrossOrigin
    @PostMapping("/addTelRecord")
    @ResponseBody
    public AjaxResult addTelRecord(@RequestBody CbkTelRecord cbkTelRecord) throws InvocationTargetException, IllegalAccessException {


        //保存服务回话到q_server
        QService qService = new QService();
        qService.setServiceId(cbkTelRecord.getLinkedid());
        qService.setServicetype("5");  //通话记录
        qService.setBeginTime(cbkTelRecord.getBegintime());
        qService.setEndTime(cbkTelRecord.getEndtime());
       // qService.setCause(String.valueOf(cbkTelRecord.getCause()));
        qService.setVoxfile(cbkTelRecord.getRecordingFile());
        qService.setCname(cbkTelRecord.getCustName());

        qService.setCallernum(cbkTelRecord.getLocalnumber());
        qService.setFromnum(cbkTelRecord.getCallerId());
        qService.setSatisfaction(cbkTelRecord.getEvaluation());
        qService.setCreatetime(cbkTelRecord.getQueueTime());
        qService.setWaittime(cbkTelRecord.getAnsweredTime());
        System.out.println("=============================:"+ cbkTelRecord.getExtension() );
        qService.setAgentid(String.valueOf(10000+Integer.valueOf((cbkTelRecord.getExtension().equals("") || cbkTelRecord.getExtension()==null)?("0"):(cbkTelRecord.getExtension()))));//前缀少1

        if (qService.getAgentid().equals("12653")){
            qService.setAgentid("11653");   //市场服务处的两个坐席合并计算
        }
        if (cbkTelRecord.getDirection().equals("out")){
            qService.setIsinside("3");
        }
        if (cbkTelRecord.getDirection().equals("in")){
            qService.setIsinside("2");
        }
        if (cbkTelRecord.getHasAnswered().equals("0")){
            qService.setState("5");
        }
        if (cbkTelRecord.getHasAnswered().equals("1")){
            qService.setState("3");
        }
        //满意度
        if (cbkTelRecord.getEvaluation().equals("1")) { //满意
            qService.setSatisfaction("2");
        }
        if (cbkTelRecord.getEvaluation().equals("2")) { //一般
            qService.setSatisfaction("3");
        }
        if (cbkTelRecord.getEvaluation().equals("3")) {  //不满意
            qService.setSatisfaction("5");
        }

        //重复电话呼出已接通的电话需要特殊处理
        //   每个电话查重， 3--接通
        if (  qService.getState().equals("3")) {
            //查找当天以前的电话
            QService query= new QService();
            query.setBeginTime(new Date().toString());
            query.setState("5");  //5---未接通

            query.setFromnum(qService.getFromnum());
            List <QService> dst =   iqServiceService.selectQServiceListState(query);
            if (dst.size() > 0 ){
                dst.forEach(item -> iqServiceService.updateQServiceState(item));//当天存在已经接通的电话，改变通话状态
            }



        }else{
            //查找当天以前的电话
            QService hr= new QService();
            hr.setBeginTime(new Date().toString());
            hr.setState("3");  //3---已接通

            hr.setFromnum(qService.getFromnum());
            List <QService> dst1 =   iqServiceService.selectQServiceListState(hr);
            if (dst1.size() > 0 ){
                qService.setState("3");  //改成已接通
            }
        }


        boolean isworktime = true;

        String tmp = qService.getBeginTime().trim().substring(11,16);
        System.out.println(qService.getBeginTime()+"==================:"+tmp);
        // 获取当前日期
        LocalDate today = LocalDate.now(ZoneId.systemDefault());

        // 获取当前日期是周几
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        QServiceNowork qServiceNowork = new QServiceNowork() ;

        // 打印复制后的目标对象
        BeanUtils.copyProperties(qServiceNowork, qService);
        System.out.println("getCallernum: " + qServiceNowork.getCallernum());
        System.out.println("getBeginTime: " + qServiceNowork.getBeginTime());

        // 测试日期
        Date testDate = new Date();
        System.out.println("Is " + testDate + " a weekend day? " + isWeekend(testDate));


        //判断周六周日
        if (this.isWeekend(testDate)){
            // 插入非工作时间的表

            qServiceNoworkService.insertQServiceNowork(qServiceNowork);


            //发送短信
            boolean isSend = smsService.send( qService.getCallernum());
             System.out.println("发送短信成功: " + qService.getCallernum());
            return toAjax(1);

        }

        //工作时间：(08:30-17:00)
        isworktime = (compTime(tmp, "08:30", "gt"))  &&  (compTime(tmp, "17:00", "lt")) ;

        if (! isworktime){
            // 插入非工作时间的表
            BeanUtils.copyProperties(qServiceNowork, qService);
            qServiceNoworkService.insertQServiceNowork(qServiceNowork);
            //发送短信
            //调用service发送短信的方法
            boolean isSend = smsService.send( qService.getCallernum());
            System.out.println("发送短信成功: " + qService.getCallernum());
            return toAjax(1);
        }

        iqServiceService.insertQService(qService);


        

        return toAjax(1);
    }

    public static boolean isWeekend(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY;
    }

    /**
     * 新增保存聊天记录
     */
    @CrossOrigin
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody ChatRecord chatRecord) {
        QChat qChat = new QChat();
        qChat.setChatTime(chatRecord.getChatTime());
        qChat.setChatSessionid(chatRecord.getChatSessionId().trim());
        List<Record> chatcontent = chatRecord.getChatContent();

        if (null == chatcontent || chatcontent.size() == 0) {
            return toAjax(0);
        }
        // 创建Gson对象
        Gson gson = new Gson();
        // 将List转换为JSON字符串
        Type listType = new TypeToken<List<Record>>() {
        }.getType();
        String json = gson.toJson(chatcontent, listType);
        System.out.println("JSON: " + json);
        qChat.setChatContent(json);
        if (null == qChatService.selectQChatList(qChat) || 0 == qChatService.selectQChatList(qChat).size()) {
            qChatService.insertQChat(qChat);
        } else {
            qChatService.updateQChat(qChat);
        }
        //保存服务回话到q_server
        QService qService = new QService();
        qService.setServiceId(chatRecord.getChatSessionId().trim());
        qService.setServicetype("6");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date now = chatRecord.getChatTime();
        String time = sdf.format(now);

        if (iqServiceService.selectQServiceByServiceId(chatRecord.getChatSessionId()) == null) {
            qService.setBeginTime(time);
            iqServiceService.insertQService(qService);
        } else {
            qService.setEndTime(time);
            //聊天次数
            qService.setDiyitem(String.valueOf(chatcontent.size()));
            iqServiceService.updateQService(qService);

        }


        //清除重复聊天记录

        return toAjax(1);
    }

    /**
     * 修改聊天记录
     */
    @CrossOrigin
    @RequiresPermissions("system:chat:edit")
    @GetMapping("/edit/{chatId}")
    public String edit(@PathVariable("chatId") Long chatId, ModelMap mmap) {
        QChat qChat = qChatService.selectQChatByChatId(chatId);
        mmap.put("qChat", qChat);
        return prefix + "/edit";
    }

    /**
     * 修改保存聊天记录
     */
    @CrossOrigin
    @RequiresPermissions("system:chat:edit")
    @Log(title = "聊天记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(QChat qChat) {
        return toAjax(qChatService.updateQChat(qChat));
    }

    /**
     * 删除聊天记录
     */
    @CrossOrigin
    @RequiresPermissions("system:chat:remove")
    @Log(title = "聊天记录", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(qChatService.deleteQChatByChatIds(ids));
    }
}
